<template>
  <div class="gulu-tabs">
    <div class="gulu-tabs-nav" ref="container">
      <div class="gulu-tabs-nav-item" v-for="(t,index) in titles" :key="index"
           :class="{selected:t===selected}" @click="select(t)"
           :ref="el => {if (t===selected) selectedItem = el}">{{ t }}
      </div>
      <div ref="indicator" class="gulu-tabs-nav-indicator"></div>
    </div>
    <div class="gulu-tabs-content">
      <component class="gulu-tabs-content-item" :is="current" :key="current.props.title"/>
    </div>
  </div>
</template>

<script lang="ts">
import Tab from "./Tab.vue";
import {computed, onMounted, ref, watchEffect} from "vue";

export default {
  name: "Tabs",
  components: {Tab},
  props: {
    selected: {
      type: String
    }
  },
  setup(props, context) {
    onMounted(()=> {
      watchEffect(()=> {
          const {width} = selectedItem.value.getBoundingClientRect()
          const {left:left1} = container.value.getBoundingClientRect()
          const {left:left2} = selectedItem.value.getBoundingClientRect()
          const left = left2 - left1
          indicator.value.style.width = width + 'px'
          indicator.value.style.left = left + 'px'
      })
    })
    const selectedItem = ref<HTMLDivElement>(null)
    const indicator = ref<HTMLDivElement>(null)
    const container = ref<HTMLDivElement>(null)
    const defaults = context.slots.default()
    defaults.forEach((tag) => {
      if (tag.type !== Tab) {
        throw new Error('Tabs 组件内的标签必须为 Tab')
      }
    })
    const select = (title: string) => {
      context.emit('update:selected', title)
    }
    const current = computed(() => defaults.find((tag) => tag.props.title === props.selected))
    const titles = defaults.map((tag) => {
      return tag.props.title
    })
    return {defaults, titles, current, select, indicator, container, selectedItem}
  }
}
</script>

<style lang="scss">
$blue: #40a9ff;
$color: #333;
$border-color: #d9d9d9;
.gulu-tabs {
  &-nav {
    display: flex;
    color: $color;
    border-bottom: 1px solid $border-color;
    position: relative;

    &-item {
      padding: 8px 0;
      margin: 0 16px;
      cursor: pointer;

      &:first-child {
        margin-left: 0;
      }

      &.selected {
        color: $blue;
      }
    }

    &-indicator {
      position: absolute;
      height: 3px;
      background: $blue;
      left: 0;
      bottom: -1px;
      width: 100px;
      transition: all 250ms;
    }
  }

  &-content {
    padding: 8px 0;
  }
}
</style>
